<template>
    <section>

        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="searchForm">
                <el-form-item>
                    <el-input v-model="searchForm.name" placeholder="部门名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="searchForm.state" clearable  placeholder="请选择状态">
                        <el-option label="启用" value="1"></el-option>
                        <el-option label="禁用" value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="loadDepartments">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="departments" v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <!--显示复选框-->
            <el-table-column type="selection" width="55">
            </el-table-column>
            <!--显示序号-->
            <el-table-column type="index" width="120"  label="序号">
            </el-table-column>
            <el-table-column prop="name" label="部门名称">
            </el-table-column>
            <el-table-column prop="sn" label="部门编号">
            </el-table-column>
            <el-table-column prop="state" label="部门状态" :formatter="formatState" >
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理" >
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门" >
            </el-table-column>

            <el-table-column label="操作">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                           :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--新增与编辑界面-->
        <el-dialog :title="title" v-model="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="部门" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="编号" prop="sn">
                    <el-input v-model="addForm.sn"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="addForm.state">
                        <el-radio class="radio" :label="1">启用</el-radio>
                        <el-radio class="radio" :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门">
                    <el-select v-model="addForm.deptId" clearable placeholder="请选择">
                        <el-option
                                v-for="item in depts"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门经理">
                    <el-select v-model="addForm.managerId" clearable placeholder="请选择">
                        <el-option
                                v-for="item in managers"
                                :label="item.username"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit">提交</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
    import {removeUser} from "../../api/api";

    export default {
        data() {
            return {
                //部门列表
                depts:[],
                //部门经理
                managers:[],
                // rules校验规则
                addFormRules: {
                    name: [
                        {required: true, message: '部门必填！!', trigger: 'blur'}
                    ],
                    sn: [
                        {required: true, message: '编号必填！!', trigger: 'blur'}
                    ]
                },
                //添加/修改弹出框中的form
                addForm:{
                    id:"",
                    name:"",
                    sn:"",
                    state:1,
                    deptId:"",
                    managerId:""
                },
                //是否显示弹出框
                addFormVisible:false,
                //弹出框标题
                title:"",
                //高级查询的form表单
                searchForm:{
                    name:"",
                    state:""
                },
                // 总条数
                total:0,
                // 当前页
                currentPage:1,
                // 每页显示条数
                pageSize:10,
                //列表选中列，选中复选框对应的地址
                sels: [],
                // 部门列表数据
                departments:[],
                // 显示加载框
                listLoading:false
            }
        },
        methods:{
            // 选中复选框触发次函数，vals表示选中的值(行值)
            selsChange(vals){
                //console.debug("选中的行",vals);
                this.sels = vals;
                //console.debug("选中的行",this.sels);
            },
            // 加载部门列表
            loadDepartments(){
                // 显示加载框
                listLoading:true;

                //传递分页参数
                let param = {
                    "currentPage": this.currentPage,
                    "pageSize": this.pageSize,
                    "name":this.searchForm.name,
                    "state":this.searchForm.state
                };

                this.$http.patch("/department",param).then((res=>{
                    //console.debug(res);
                    //this.departments = res.data;
                    let {result, total} = res.data;
                    this.departments = result;
                    this.total = total;
                    // 关闭加载框
                    listLoading:false;
                }));
            },
            //格式化指定列的值  row:当前行对应的值   column:列属性的介绍
            formatState(row, column){
                return row.state ? "启用" : "禁用";
            },
            //批量删除按钮
            batchRemove(){
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.patch("/department/batchRemove",this.sels).then((res => {
                        let {success,msg} = res.data;
                        if(success){
                            this.loadDepartments();
                        }else{
                            this.$message.error(msg);
                        }
                    }));
                }).catch(() => {

                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.$http.delete("/department/"+row.id).then((res=>{
                        //console.debug(res);
                        let {success,msg} = res.data;
                        if(success){
                            this.loadDepartments();
                        }else{
                            this.$message.error(msg);
                        }
                    }));
                }).catch(() => {

                });
            },
            //页码发生改变的时候触发此函数     参数val，表示页码
            handleCurrentChange(val){
                //重新设置当前页
                this.currentPage = val;
                //刷新页面
                this.loadDepartments();
            },
            //新增弹出窗体
            handleAdd(){
                //设置标题
                this.title = "新增";
                //重置
                if(this.$refs["addForm"]){
                    this.$refs["addForm"].resetFields();
                }
                //清空form表单
                for(var k in this.addForm){
                    this.addForm[k] = "";
                }
                // 默认启用的状态
                this.addForm.state = 1;
                //显示弹出框
                this.addFormVisible = true;
            },
            //加载所有的部门列表
            loadAllDepartments(){
                this.$http.patch("/department/loadAll").then((res => {
                    //console.debug("所有部门列表",res);
                    this.depts = res.data;
                }));
            },
            //加载所有的员工列表
            loadAllEmployees(){
                this.$http.patch("/employee/loadAll").then((res => {
                    //console.debug("所有员工列表",res);
                    this.managers = res.data;
                }));
            },
            //提交按钮注册事件
            addSubmit(){
                if(this.addForm.deptId){
                    //给addForm动态添加属性，封装成parent对象
                    this.addForm.parent = {"id":this.addForm.deptId}
                }else{
                    this.addForm.parent = {"id":""}
                }
                if(this.addForm.managerId){
                    //给addForm动态添加属性，封装成manager对象
                    this.addForm.manager = {"id": this.addForm.managerId};
                }else{
                    this.addForm.manager = {"id":""}
                }
                //必须验证通过之后，才执行if语句中的内容
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$http.put("/department", this.addForm).then((res => {
                            let {success, msg} = res.data;
                            if(success){
                                //刷新列表
                                this.loadDepartments();
                                //关闭弹出框
                                this.addFormVisible = false;
                            }else{
                                this.$message.error(msg);
                            }
                        }));
                    }
                });
            },
            //编辑弹出框
            handleEdit(index,row){
                //循环form表单（解决普通赋值）
                for(var k in this.addForm){
                    this.addForm[k] = row[k];
                }
                //给部门经理赋值
                if(row.manager){
                    this.addForm.managerId = row.manager.id;
                }
                //给部门赋值
                if(row.parent){
                    this.addForm.deptId = row.parent.id;
                }
                //弹出窗体
                this.addFormVisible = true;
            }
        },
        mounted() {
            //加载部门列表(分页)
            this.loadDepartments();
            //加载部门列表
            this.loadAllDepartments();
            //加载部门经理列表
            this.loadAllEmployees();
        }
    }
</script>